package site.xuxingcan.autodownload;

import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.TrafficStats;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private EditText mMax;
    private TextView mText;
    private EditText sleep_times;
    private EditText mDownload_1;
    private EditText mDownload_2;
    private EditText mDownload_3;
    private EditText mDownload_4;
    private EditText mDownload_5;
    private Button mStart;
    private int mMaxLiuliang;
    private int sleepTime;
    private String download1;
    private String download2;
    private String download3;
    private String download4;
    private String download5;
    private ArrayList<DownloadThread> mDownloadThreadArrayList = new ArrayList<>();
    private Timer mTimer;
    private Button mEnd;
    private TextView mHelp;
    private ArrayList<String> aikanList = new ArrayList<>();
    private ArrayList<String> tianyiList = new ArrayList<>();
    private ArrayList<String> otherList = new ArrayList<>();
    private CheckBox aikanCheckbox;
    private CheckBox tianyiCheckbox;
    private CheckBox otherCheckbox;

    private void bindViews() {
        mMax = (EditText) findViewById(R.id.max);
        sleep_times = (EditText) findViewById(R.id.sleep_times);
        mDownload_1 = (EditText) findViewById(R.id.download_1);
        mDownload_2 = (EditText) findViewById(R.id.download_2);
        mDownload_3 = (EditText) findViewById(R.id.download_3);
        mDownload_4 = (EditText) findViewById(R.id.download_4);
        mDownload_5 = (EditText) findViewById(R.id.download_5);
        mStart = (Button) findViewById(R.id.start);
        mEnd = (Button) findViewById(R.id.end);
        mText = (TextView) findViewById(R.id.text);
        mHelp = (TextView) findViewById(R.id.help);
        aikanCheckbox = (CheckBox) findViewById(R.id.aikan_checkbox);
        tianyiCheckbox = (CheckBox) findViewById(R.id.tianyi_checkbox);
        otherCheckbox = (CheckBox) findViewById(R.id.other_checkbox);
    }

    public long getTraffic() {
        int uid = getApplicationInfo().uid;
        return TrafficStats.getUidRxBytes(uid) + TrafficStats.getUidTxBytes(uid);
    }

    private long currentTraffice = 0;
    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mHandler = new Handler(Looper.getMainLooper());
        bindViews();
        mEnd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mStart.setEnabled(true);
                mEnd.setEnabled(false);
                mMax.setEnabled(true);
                mDownload_1.setEnabled(true);
                mDownload_2.setEnabled(true);
                mDownload_3.setEnabled(true);
                mDownload_4.setEnabled(true);
                mDownload_5.setEnabled(true);
                aikanCheckbox.setEnabled(true);
                tianyiCheckbox.setEnabled(true);
                otherCheckbox.setEnabled(true);
                mText.setText("任务被结束");
                try {
                    for (DownloadThread mDownloadThread : mDownloadThreadArrayList) {
                        mDownloadThread.setStop(true);
                    }
                    mDownloadThreadArrayList.clear();
                    mTimer.cancel();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        mStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final boolean isAikan = aikanCheckbox.isChecked();
                final boolean isTianyi = tianyiCheckbox.isChecked();
                final boolean isOther = otherCheckbox.isChecked();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        aikanList.clear();
                        tianyiList.clear();
                        otherList.clear();
                        if (isAikan) {
                            try {
                                AVQuery<AVObject> query = new AVQuery<>("Aikan_URL");
                                List<AVObject> list = query.find();
                                for (AVObject avObject : list) {
                                    aikanList.add(avObject.getString("URL"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        if (isTianyi) {
                            try {
                                AVQuery<AVObject> query = new AVQuery<>("Tianyi_URL");
                                List<AVObject> list = query.find();
                                for (AVObject avObject : list) {
                                    tianyiList.add(avObject.getString("URL"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        if (isOther) {
                            try {
                                AVQuery<AVObject> query = new AVQuery<>("Other_URL");
                                List<AVObject> list = query.find();
                                for (AVObject avObject : list) {
                                    otherList.add(avObject.getString("URL"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    mMaxLiuliang = Integer.parseInt(mMax.getText().toString());
                                    sleepTime = Integer.parseInt(sleep_times.getText().toString());
                                    download1 = mDownload_1.getText().toString();
                                    download2 = mDownload_2.getText().toString();
                                    download3 = mDownload_3.getText().toString();
                                    download4 = mDownload_4.getText().toString();
                                    download5 = mDownload_5.getText().toString();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Toast.makeText(MainActivity.this, "输入有误！", Toast.LENGTH_LONG).show();
                                    return;
                                }
                                mTimer = new Timer();
                                mTimer.schedule(new TimerTask() {
                                    @Override
                                    public void run() {
                                        final long tr = (getTraffic() - currentTraffice) / 1024 / 1024;
                                        if (tr >= mMaxLiuliang) {
                                            try {
                                                for (DownloadThread mDownloadThread : mDownloadThreadArrayList) {
                                                    mDownloadThread.setStop(true);
                                                }
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                            mHandler.post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    mStart.setEnabled(true);
                                                    mEnd.setEnabled(false);
                                                    mMax.setEnabled(true);
                                                    mDownload_1.setEnabled(true);
                                                    mDownload_2.setEnabled(true);
                                                    mDownload_3.setEnabled(true);
                                                    mDownload_4.setEnabled(true);
                                                    mDownload_5.setEnabled(true);
                                                    aikanCheckbox.setEnabled(true);
                                                    tianyiCheckbox.setEnabled(true);
                                                    otherCheckbox.setEnabled(true);
                                                    mText.setText("任务完成");
                                                    mTimer.cancel();
                                                    startAlarm();
                                                }
                                            });
                                        } else {
                                            mHandler.post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    mText.setText("当前流量：" + (getTraffic() - currentTraffice) / 1024 / 1024 + "M");
                                                    boolean isFinish = true;
                                                    for (DownloadThread mDownloadThread : mDownloadThreadArrayList) {
                                                        if (!mDownloadThread.isFinish()) {
                                                            isFinish = false;
                                                        }
                                                    }
                                                    if (isFinish) {
                                                        mStart.setEnabled(true);
                                                        mEnd.setEnabled(false);
                                                        mMax.setEnabled(true);
                                                        mDownload_1.setEnabled(true);
                                                        mDownload_2.setEnabled(true);
                                                        mDownload_3.setEnabled(true);
                                                        mDownload_4.setEnabled(true);
                                                        mDownload_5.setEnabled(true);
                                                        aikanCheckbox.setEnabled(true);
                                                        tianyiCheckbox.setEnabled(true);
                                                        otherCheckbox.setEnabled(true);
                                                        mText.setText("任务完成");
                                                        mTimer.cancel();
                                                        startAlarm();
                                                    }
                                                }
                                            });
                                        }
                                    }
                                }, 1000, 1000);
                                download();
                            }
                        });
                    }
                }).start();
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                String text = "无";
                try {
                    AVQuery<AVObject> query = new AVQuery<>("Text");
                    List<AVObject> list = query.find();
                    if (list.size() != 0) {
                        AVObject avObject = list.get(0);
                        text = avObject.getString("text");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (!TextUtils.isEmpty(text)) {
                    final String finalText = text;
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            mHelp.setText(finalText);
                        }
                    });
                }
                try {
                    AVQuery<AVObject> query = new AVQuery<>("URL");
                    query.orderByAscending("order");
                    final List<AVObject> list = query.find();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (list.size() > 0) {
                                AVObject avObject = list.get(0);
                                mDownload_1.setText(avObject.getString("URL"));
                            }
                            if (list.size() > 1) {
                                AVObject avObject = list.get(1);
                                mDownload_2.setText(avObject.getString("URL"));
                            }
                            if (list.size() > 2) {
                                AVObject avObject = list.get(2);
                                mDownload_3.setText(avObject.getString("URL"));
                            }
                            if (list.size() > 3) {
                                AVObject avObject = list.get(3);
                                mDownload_4.setText(avObject.getString("URL"));
                            }
                            if (list.size() > 4) {
                                AVObject avObject = list.get(4);
                                mDownload_5.setText(avObject.getString("URL"));
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void download() {
        mDownloadThreadArrayList.clear();
        currentTraffice = getTraffic();
        if (tianyiList.size() != 0) {
            DownloadThread mDownloadThread = new DownloadThread(tianyiList, 1, sleepTime);
            mDownloadThread.start();
            mDownloadThreadArrayList.add(mDownloadThread);
        }
        if (aikanList.size() != 0) {
            DownloadThread mDownloadThread = new DownloadThread(aikanList, 2, sleepTime);
            mDownloadThread.start();
            mDownloadThreadArrayList.add(mDownloadThread);
        }
        if (otherList.size() != 0) {
            DownloadThread mDownloadThread = new DownloadThread(otherList, 3, sleepTime);
            mDownloadThread.start();
            mDownloadThreadArrayList.add(mDownloadThread);
        }
//        if (!TextUtils.isEmpty(download1)) {
//            DownloadThread mDownloadThread = new DownloadThread(download1, 1);
//            mDownloadThread.start();
//            mDownloadThreadArrayList.add(mDownloadThread);
//        }
//        if (!TextUtils.isEmpty(download2)) {
//            DownloadThread mDownloadThread = new DownloadThread(download2, 2);
//            mDownloadThread.start();
//            mDownloadThreadArrayList.add(mDownloadThread);
//        }
//        if (!TextUtils.isEmpty(download3)) {
//            DownloadThread mDownloadThread = new DownloadThread(download3, 3, sleepTime);
//            mDownloadThread.start();
//            mDownloadThreadArrayList.add(mDownloadThread);
//        }
        if (!TextUtils.isEmpty(download4)) {
            DownloadThread mDownloadThread = new DownloadThread(download4, 4, sleepTime);
            mDownloadThread.start();
            mDownloadThreadArrayList.add(mDownloadThread);
        }
        if (!TextUtils.isEmpty(download5)) {
            DownloadThread mDownloadThread = new DownloadThread(download5, 5, sleepTime);
            mDownloadThread.start();
            mDownloadThreadArrayList.add(mDownloadThread);
        }
        mStart.setEnabled(false);
        mEnd.setEnabled(true);
        mMax.setEnabled(false);
        mDownload_1.setEnabled(false);
        mDownload_2.setEnabled(false);
        mDownload_3.setEnabled(false);
        mDownload_4.setEnabled(false);
        mDownload_5.setEnabled(false);
        aikanCheckbox.setEnabled(false);
        tianyiCheckbox.setEnabled(false);
        otherCheckbox.setEnabled(false);
        mText.setText("当前流量：" + (getTraffic() - currentTraffice) / 1024 / 1024 + "M");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.update:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String url = UpdateUtil.shouldUpdate(MainActivity.this);
                        if (TextUtils.isEmpty(url)) {
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "当前版本已经是最新版本！", Toast.LENGTH_SHORT).show();
                                }
                            });
                        } else {
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "检查到新版本，正在下载中。", Toast.LENGTH_SHORT).show();
                                }
                            });
                            final File mFile = UpdateUtil.downloadApk(url);
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    Intent intent = new Intent(Intent.ACTION_VIEW);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    intent.setDataAndType(Uri.parse("file://" + mFile.getAbsolutePath()), "application/vnd.android.package-archive");
                                    MainActivity.this.startActivity(intent);
                                }
                            });

                        }
                    }
                }).start();
                Toast.makeText(this, "检查更新中...", Toast.LENGTH_SHORT).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void startAlarm() {
        try {
            final MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.echo);
            mMediaPlayer.setLooping(true);//设置循环
//            mMediaPlayer.prepare();
            mMediaPlayer.start();
            AlertDialog.Builder builder = new AlertDialog.Builder(this);  //先得到构造器
            builder.setTitle("提示"); //设置标题
            builder.setMessage("任务完成"); //设置内容
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { //设置确定按钮
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss(); //关闭dialog
                    mMediaPlayer.stop();
                }
            });
            builder.create().show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
